import _ from 'lodash';
import { Product } from '../entities/product';
import { EntityRepository, Repository } from 'typeorm';
import { ProductPageQuery } from '../dtos';
import buildPaginator from 'pagination-apis';

export interface IProductRepository {
  findForPage(pageQuery: ProductPageQuery): Promise<any>;
}

@EntityRepository(Product)
export class ProductRepository extends Repository<Product> implements IProductRepository {

  async findForPage(pageQuery: ProductPageQuery): Promise<any> {
    const { skip, limit, paginate } = buildPaginator({ page: pageQuery.currentPage || 1, limit: pageQuery.pageSize || 10 });
    let query = this.createQueryBuilder('productPage');
    if (pageQuery.name) {
      query.where('name like :name', { name: '%' + pageQuery.name + '%' });
    }
    // console.log(query.getSql());
    const [data, total] = await query.addOrderBy('id', 'DESC')
      .skip(skip)
      .take(limit)
      .getManyAndCount();
    return paginate(data, total);
  }

}